package com.logic.landseaserver.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.logic.system.service.IConfigurationService;
import com.logic.system.service.impl.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.logic.common.domain.Code;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.domain.Order;
import com.logic.landseaserver.domain.VerificationCode;
import com.logic.landseaserver.persistence.read.OrderReadMapper;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.persistence.write.OrderWriteMapper;
import com.logic.landseaserver.service.IOrderService;
import com.logic.landseaserver.service.ISendSmsService;
import com.logic.landseaserver.ws.dto.OrderDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailDTO;
import com.logic.system.service.ICodeService;
import com.logic.system.service.impl.AddressService;
import com.logic.system.ws.dto.AddressDto;

/**
 * @Author: Drake
 * @Date: 2017/4/17
 * @Description: 预约工程接口实现类
 */
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderReadMapper orderReadMapper;

    @Autowired
    private OrderWriteMapper orderWriteMapper;

    @Autowired
    private ProjectReadMapper projectReadMapper;

    @Autowired
    private ISendSmsService iSendSmsServiceImpl;

    @Autowired
    private SendMsgConfiguration sendMsgConfiguration;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ICodeService codeService;
    @Autowired
    private IConfigurationService configurationService;

    @Override
    public void delete(String arg0) throws BusinessException {
        // TODO Auto-generated method stub

    }

    @Override
    public OrderDTO get(Integer arg0) throws BusinessException {

        return orderReadMapper.getOrderDetail(arg0);
    }

    @Override
    public int insertOrder(OrderDTO orderDTO) throws BusinessException {
        int orderInt = -1;
        if (validateForInsert(orderDTO)) {//需补充验证
            Order order = new Order();
            int orderId;
            setOrderByOrderDTO(order, orderDTO);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String dateNowStr = sdf.format(date);
            String orderCode = null;//TODO 订单编号规则为来源（FR/BA）+ 8位日期 + 3位流水号
            String orderFromPage;//预约来源
            if (orderDTO.getUserId() == null) {//null时为用户操作，不为null时管理员操作
                orderFromPage = "_LOS1";
                VerificationCode verification = new VerificationCode();
                verification.setCellPhone(orderDTO.getOrderPersonTel());
                verification.setVerificationCode(orderDTO.getVerificationCode());
                verification.setOper("order");
                //增加万能验证码
                String verCod = verification.getVerificationCode();
                if (!("171717".equals(verCod))) {
                    iSendSmsServiceImpl.checkVerification(verification);//验证码判断
                }
                order.setCreatedDtm(new Date());
                order.setCreatedBy(orderDTO.getUserId());
                order.setOrderFromPage(orderFromPage);
                orderWriteMapper.insertSelective(order);
                orderId = order.getId();
                if (orderId < 10) {
                    orderCode = "FR" + dateNowStr + "00" + orderId;
                } else if (orderId >= 10 && orderId < 100) {
                    orderCode = "FR" + dateNowStr + "0" + orderId;
                } else if (orderId >= 100) {
                    orderCode = "FR" + dateNowStr + orderId;
                }
                order.setOrderCode(orderCode);
                orderWriteMapper.updateByPrimaryKeySelective(order);
                orderInt = order.getId();
            } else {
                orderFromPage = "_LOS2";
                order.setCreatedDtm(new Date());
                order.setCreatedBy(orderDTO.getUserId());
                order.setOrderFromPage(orderFromPage);
                orderWriteMapper.insertSelective(order);
                orderId = order.getId();
                if (orderId < 10) {
                    orderCode = "BA" + dateNowStr + "00" + orderId;
                } else if (orderId >= 10 && orderId < 100) {
                    orderCode = "BA" + dateNowStr + "0" + orderId;
                } else if (orderId >= 100) {
                    orderCode = "BA" + dateNowStr + orderId;
                }
                order.setOrderCode(orderCode);
                orderWriteMapper.updateByPrimaryKeySelective(order);
                orderInt = order.getId();
            }
        }
        return orderInt;
    }

    @Override
    public List<OrderDTO> query(QueryUtil queryUtil) {
        List<OrderDTO> result = orderReadMapper.getOrderDTOList(queryUtil);
        return result;
    }

    @Override
    public void update(Object obj) throws BusinessException {

    }

    @Override
    public Boolean validate(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Boolean validateForDelete(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Boolean validateForInsert(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        OrderDTO orderDTO = (OrderDTO) arg0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(orderDTO.getOrderTime());
        int count = orderReadMapper.selectByColumns(dateStr, orderDTO.getOrderPersonTel(), orderDTO.getPrjId());
        if (count > 0) {
            return Boolean.valueOf(false);
        }
        return Boolean.valueOf(true);
    }

    @Override
    public Boolean validateForUpdate(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }


    //通过orderDTO创建order
    public void setOrderByOrderDTO(Order order, OrderDTO orderDTO) {


        if (!StringUtils.isEmpty(orderDTO.getOrderPersonName()))
            order.setOrderPersonName(orderDTO.getOrderPersonName());
        if (!StringUtils.isEmpty(orderDTO.getOrderPersonSex()))
            order.setOrderPersonSex(orderDTO.getOrderPersonSex());
        if (!StringUtils.isEmpty(orderDTO.getOrderPersonTel()))
            order.setOrderPersonTel(orderDTO.getOrderPersonTel());
        if (!StringUtils.isEmpty(orderDTO.getOrderTime()))
            order.setOrderTime(orderDTO.getOrderTime());
        if (!StringUtils.isEmpty(orderDTO.getAddress()))
            order.setAddress(orderDTO.getAddress());
        if (!StringUtils.isEmpty(orderDTO.getPrjId()))
            order.setPrjId(orderDTO.getPrjId());
        if (!StringUtils.isEmpty(orderDTO.getPrjName()))
            order.setPrjName(orderDTO.getPrjName());
        if (!StringUtils.isEmpty(orderDTO.getRoomTypeCode()))
            order.setRoomTypeCode(orderDTO.getRoomTypeCode());
        if (!StringUtils.isEmpty(orderDTO.getRoomTypeName()))
            order.setRoomTypeName(orderDTO.getRoomTypeName());
//		if(!StringUtils.isEmpty(orderDTO.getComment()))
        order.setComment(orderDTO.getComment());
        if (!StringUtils.isEmpty(orderDTO.getStatus()))
            order.setStatus(orderDTO.getStatus());
    }

    @Override
    public int insert(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void editOrder(OrderDTO orderDTO) throws BusinessException {
        Order order = orderReadMapper.selectByPrimaryKey(orderDTO.getId());
        setOrderByOrderDTO(order, orderDTO);
        order.setLastModifiedBy(orderDTO.getUserId());
        order.setLastModifiedDtm(new Date());
        orderWriteMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void deleteOrder(Integer id) throws BusinessException {
        Order order = new Order();
        order.setId(id);
        orderWriteMapper.deleteByPrimaryKey(id);
        order.setLastModifiedBy(1);//假设当前操作管理员id为1
        order.setLastModifiedDtm(new Date());
        orderWriteMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public String getValueByCode(String code) throws BusinessException {
        return orderReadMapper.getValueByCode(code);
    }

    @Override
    public void sendMessage(OrderDTO orderDTO) throws BusinessException {

        //尊敬的李艳艳先生，您已成功预约朗诗寓新街口店，诚邀您于2017-06-20莅临南京市秦淮区中山东路56号新华书店大厦（近洪武路）现场看房。联系电话：0519-88888888、18105179303。
        String name = orderDTO.getOrderPersonName();

        Code code= codeService.getCode(orderDTO.getOrderPersonSex());
        if(code != null) {
            name += code.getCodeDescTr();
        }

        String prjName = orderDTO.getPrjName();
        int prjId = orderDTO.getPrjId();
        String date = new DateUtil().convertDate3(orderDTO.getOrderTime());
        ProjectDetailDTO projectDto = projectReadMapper.getProjectDetail(prjId);
        //项目地址、电话、店长电话不可为空
        String address = "";
        String phone = "";
        String mobile = "";
        if (projectDto != null) {
            StringBuffer fullAddress = new StringBuffer();

            if (projectDto.getAddressId() != null) {
                AddressDto addressDto = addressService.queryDetailById(projectDto.getAddressId());
                if (addressDto != null) {
                    fullAddress.append(addressDto.getCity() == null ? "" : addressDto.getCity()).append(addressDto.getCounty() == null ? "" : addressDto.getCounty()).append(addressDto.getAddressLine() == null ? "" : addressDto.getAddressLine());

                }
            }
            fullAddress.append("现场看房");
            address = fullAddress.toString();
            phone = projectDto.getTelephone();
            mobile = projectDto.getChargeUserMobile();

            //Changed by Daniel for phone settings
            if(StringUtils.isEmpty(phone)) {
                if (!StringUtils.isEmpty(mobile)) {
                    phone = mobile;
                }
            } else {
                if (!StringUtils.isEmpty(mobile)) {
                    phone += "、" + mobile;
                }
            }

        }
        if (phone == null) {
            phone = "";
        } //优化短信显示

        //String messageCode, String cellPhone, String params
        String params = " {'project':'" + prjName + "','date':'" + date + "','address':'" + address + "','contact':'" + phone + "'}";
        //尊敬的${name}，您已成功预约朗诗寓${project}，诚邀您于${date}莅临${address}。联系电话：${contact}。
        String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
        SMSUtil.sendSms(sendMsgConfiguration.getOrderSuccessCode(), orderDTO.getOrderPersonTel(), params,signName);
    }
}
